<template>
  <div class="relative h-full w-full">
    <div class="absolute top-10 left-10 z-10">
      <el-select
        v-model="keywords"
        filterable
        remote
        reserve-keyword
        placeholder="请输入关键词搜索位置"
        :remote-method="remoteMethod"
        :loading="loading"
        :clearable="true"
        style="width: 400px"
        @change="currentSelect"
      >
        <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id" class="one-text">
          <span style="float: left">{{ item.name }}</span>
          <span style="float: right; color: #8492a6; font-size: 13px">{{ item.district }}</span>
        </el-option>
      </el-select>
    </div>

    <div id="amapContainer" class="w-full h-full" />
  </div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader'

window._AMapSecurityConfig = {
  // 安全密钥
  securityJsCode: '67543bbe51d77f15ffbb4eeaefe72549'
}

export default {
  props: {
    obj: { type: Object, default: () => ({}) }
  },
  data() {
    return {
      // 地图实例
      map: null,
      // 标记点
      marker: '',
      // 地址逆解析
      geoCoder: null,
      // 搜索提示
      AutoComplete: null,
      // 搜索关键字
      keywords: '',
      // 位置信息
      locationInfo: {
        lng: '',
        lat: '',
        address: '',
        adcode: '' // 地区编码
      },
      // 搜索节流阀
      loading: false,
      // 搜索提示信息
      options: []
    }
  },

  async mounted() {
    await this.initMap()
    this.$watch('obj.longitude', {
      handler(newVal) {
        console.log('监听经度', newVal)
        if (newVal && this.obj.latitude) {
          this.locationInfo.lng = newVal
          this.locationInfo.lat = this.obj.latitude
          // 清除点
          this.removeMarker()
          // 标记点
          this.setMapMarker()
        }
      },
      immediate: true
    })
  },

  methods: {
    initMap() {
      return new Promise((resolve, reject) => {
        AMapLoader.load({
          // 你申请的Key
          key: 'a1c11507a262375314c63fa0439a727d',
          version: '2.0',
          // 需要用到的插件
          plugins: ['AMap.Geocoder', 'AMap.AutoComplete']
        })
          .then(AMap => {
            this.map = new AMap.Map('amapContainer', {
              viewMode: '3D', // 是否为3D地图模式
              zoom: 13, // 初始化地图级别
              center: [116.397428, 39.90923] // 初始化地图中心点位置
            })
            // 地址逆解析插件
            this.geoCoder = new AMap.Geocoder({
              city: '010', // 城市设为北京，默认：“全国”
              radius: 1000 // 范围，默认：500
            })
            // 搜索提示插件
            this.AutoComplete = new AMap.AutoComplete({ city: '全国' })
            resolve(true)
            // 点击获取经纬度;
            this.map.on('click', e => {
              // 获取经纬度
              this.locationInfo.lng = e.lnglat.lng
              this.locationInfo.lat = e.lnglat.lat
              // 清除点
              this.removeMarker()
              // 标记点
              this.setMapMarker()
            })
          })
          .catch(err => {
            // 错误
            console.log('加载地图失败', err)
            reject(err)
          })
      })
    },

    // 标记点
    setMapMarker() {
      // 自动适应显示想显示的范围区域
      this.map.setFitView()
      this.marker = new AMap.Marker({
        map: this.map,
        position: [this.locationInfo.lng, this.locationInfo.lat]
      })
      // 逆解析地址
      this.toGeoCoder()
      this.map.setFitView()
      this.map.add(this.marker)
      this.$emit('selected', this.locationInfo)
    },

    // 清除点
    removeMarker() {
      if (this.marker) {
        this.map.remove(this.marker)
      }
    },

    // 逆解析地址
    toGeoCoder() {
      const lnglat = [this.locationInfo.lng, this.locationInfo.lat]
      this.geoCoder.getAddress(lnglat, (status, result) => {
        if (status === 'complete' && result.regeocode) {
          this.locationInfo.address = result.regeocode.formattedAddress
        }
      })
    },

    // 搜索
    remoteMethod(query) {
      console.log(query)
      if (query !== '') {
        this.loading = true
        setTimeout(() => {
          this.loading = false
          this.AutoComplete.search(query, (status, result) => {
            console.log('搜索结果', status, result)
            this.options = result.tips?.filter(item => item.id) || []
          })
        }, 200)
      } else {
        this.options = []
      }
    },

    // 选中提示
    currentSelect(val) {
      console.log('选中提示', val)
      // 清空时不执行后面代码
      if (!val) return
      const currentVal = this.options?.find(item => item.id === val)
      this.locationInfo = {
        lng: currentVal.location.lng,
        lat: currentVal.location.lat,
        address: currentVal.district + currentVal.address,
        adcode: currentVal.adcode
      }
      // 清除点
      this.removeMarker()
      // 标记点
      this.setMapMarker()
      this.$emit('selected', this.locationInfo)
    },

    // 重置搜索
    resetSearch() {
      this.keywords = ''
      this.options = []
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .amap-copyright,
::v-deep .amap-logo {
  display: none !important;
}
</style>
